import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:happy_elf_app/routes/config.dart';
import 'package:happy_elf_app/utils/globalKey.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:happy_elf_app/store/config.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark));

  runApp(Store.init(MyAppNew()));
}

class MyAppNew extends StatefulWidget {
  @override
  MyApp createState() => MyApp();
}

class MyApp extends State<MyAppNew> with WidgetsBindingObserver {
  final RouteConfig router = RouteConfig();

  static final RouteObserver<PageRoute> routeObserver =
      RouteObserver<PageRoute>();

  // 监听路由变化
  MaterialPageRoute onGenerateRoute(RouteSettings settings) {
    // 获取声明的路由页面函数
    // String nameCN = router.routes[settings.name]!['nameCN'] ?? settings.name;
    var viewBuilder = router.routes[settings.name]!['builder'];
    if (viewBuilder != null) {
      if (settings.arguments != null) {
        // 创建路由页面并携带参数
        return MaterialPageRoute(
            settings: RouteSettings(name: settings.name),
            builder: (context) =>
                viewBuilder(context, arguments: settings.arguments));
      } else {
        return MaterialPageRoute(
          settings: RouteSettings(name: settings.name),
          builder: (context) => WillPopScope(
            child: viewBuilder(context),
            onWillPop: () async {
              return true;
            },
          ),
        );
      }
    }

    // 默认到登录
    return MaterialPageRoute(
      builder: (context) => WillPopScope(
        child: router.routes['Login']!['builder'](context),
        onWillPop: () async {
          return true;
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp, //只能纵向
      DeviceOrientation.portraitDown, //只能纵向
    ]);
    return MaterialApp(
      navigatorKey: Global.navigatorKey,
      title: '幸福精灵',
      initialRoute: "Login",
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      builder: EasyLoading.init(),
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('zh', 'CN'),
        Locale('en', 'US'),
      ],
      locale: Locale('zh', 'CN'),
      navigatorObservers: [MyApp.routeObserver],
      onGenerateRoute: onGenerateRoute,
      // home: const Login(),
    );
  }
}
